package com.malbbmsomanager.reports;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.malbbmsomanager.DM_BBM_InvoiceMenu;
import com.malbbmsomanager.R;
import com.malbbmsomanager.print.DM_BBM_InvoiceSalesOrder_PrintPreview;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_BBM_Outlet_Discount_Summary extends Activity implements
		ActionBar.OnNavigationListener {

	private static final String TAG = null;
	// Database Name.
	private static final String DATABASE_NAME = "dminvoicemanagerbbm.db";
	// ****Main Transaction Table****
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0";

	int toDayTag = 0;
	DecimalFormat numberFormat = new DecimalFormat("#.000000");
	DecimalFormat numberFormatAmt = new DecimalFormat("#,###,###.00");
	MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
	// DateDiscountValue,DateTaxValue,DateSalesOrdValue
	BigDecimal DateDiscountValue = new BigDecimal("0.00");
	BigDecimal DateSalesOrdValue = new BigDecimal("0.00");
	BigDecimal DateSalesDisPer = new BigDecimal("0.00");
	// TotalDiscountValue,TotalTaxValue,TotalSalesOrdValue
	BigDecimal TotalDiscountValue = new BigDecimal("0.00");
	BigDecimal TotalSalesOrdValue = new BigDecimal("0.00");
	BigDecimal TotalSalesDisPer = new BigDecimal("0.00");

	BigDecimal perHundred = new BigDecimal("100.00");

	EditText dmreportfromdate, dmreporttodate, dmdisplayrepname;
	TextView txtHeadingReports, totalSum, totalTonage;
	TextView recordtot_1, recordtot_2, recordtot_3, recordtot_4, recordtot_5,
			recordtot_6;

	String currentReportName, selectFromDate, selectToDate, currentUserTemp,
			currentUserPrefix, UserLocCode, selectFromDateNow, selectToDateNow;

	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	Date date, LoadingFromDate, LoadingToDate, LoadingOriDate;
	private ActionBar actionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_outlet_discount_summary);

		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_0", "item_result_1",
				"item_result_2", "item_result_3", "item_result_4",
				"item_result_5" };

		int[] totrdes = new int[] { R.id.record_0, R.id.record_1,
				R.id.record_2, R.id.record_3, R.id.record_4, R.id.record_5 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);

		Cursor allrowitemsdes = null;
		String query;
		query = "SELECT * FROM FOrdHed Where Active_State != '1' GROUP BY DebCode";
		// ***Select sum queries need seperately 8 to for the combinations
		allrowitemsdes = mydb.rawQuery(query, null);
		Log.v(TAG, "Count:" + allrowitemsdes.getCount());
		String PreTxnDate = "000";
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					String ParentRefNo = allrowitemsdes.getString(1);
					String DiscountMain = allrowitemsdes.getString(15);
					String RetailerNo = allrowitemsdes.getString(8);
					String RetailerName = allrowitemsdes.getString(38);
					if(DiscountMain.equals("0.00")){
						
					}
					else{
						Cursor displaySummary = null;
						String querySummary;

						querySummary = "SELECT * FROM FOrdHed Where Active_State != '1' AND DebCode ='"
								+ RetailerNo + "'";
						displaySummary = mydb.rawQuery(querySummary, null);

						if (displaySummary != null) {
							if (displaySummary.getCount() > 0) {
								int printIndex = 0;
								while (displaySummary.moveToNext()) {
									printIndex = printIndex + 1;
									String RefNo = displaySummary.getString(1);
									String Discount = displaySummary.getString(15);
									String Value = displaySummary.getString(21);
									Log.v(TAG, "RefNo    :" + RefNo);
									Log.v(TAG, "Discount :" + Discount);
									Log.v(TAG, "Value    :" + Value);
									BigDecimal DisPerValue = new BigDecimal("0.00");
									BigDecimal DiscountValue = new BigDecimal(
											Discount.replaceAll("[,]", ""));
									BigDecimal SalesOrdValue = new BigDecimal(
											Value.replaceAll("[,]", ""));

									try {
										DisPerValue = DiscountValue.divide(
												SalesOrdValue, mc);
										DateDiscountValue = DateDiscountValue
												.add(DiscountValue);
										DateSalesDisPer = DateDiscountValue.divide(
												DateSalesOrdValue, mc);
									} catch (Exception e) {
										Log.v(TAG, "Exception    :" + e);
									}
									DisPerValue = DisPerValue.multiply(perHundred);

									DateSalesOrdValue = DateSalesOrdValue
											.add(SalesOrdValue);

									DateSalesDisPer = DateSalesDisPer
											.multiply(perHundred);
									DateSalesDisPer = DateSalesDisPer
											.add(DisPerValue);
									/*
									 * DateSalesDisPer = DateSalesDisPer.setScale(2,
									 * BigDecimal.ROUND_HALF_DOWN);
									 */
									SalesOrdValue = SalesOrdValue.setScale(2,
											BigDecimal.ROUND_HALF_DOWN);
									DiscountValue = DiscountValue.setScale(2,
											BigDecimal.ROUND_HALF_DOWN);
									DisPerValue = DiscountValue.setScale(2,
											BigDecimal.ROUND_HALF_DOWN);
									// perHundred
									HashMap<String, String> maptrdes = new HashMap<String, String>();

									if (printIndex == 1) {
										maptrdes.put("item_result_0", RetailerNo);
										maptrdes.put("item_result_1", RetailerName);
										maptrdes.put("item_result_2", RefNo);
										maptrdes.put("item_result_3", ""
												+ SalesOrdValue);
										maptrdes.put("item_result_4", ""
												+ DiscountValue);
										maptrdes.put("item_result_5", ""
												+ DisPerValue);
									} else {
										maptrdes.put("item_result_0", "");
										maptrdes.put("item_result_1", "");
										maptrdes.put("item_result_2", RefNo);
										maptrdes.put("item_result_3", ""
												+ SalesOrdValue);
										maptrdes.put("item_result_4", ""
												+ DiscountValue);
										maptrdes.put("item_result_5", ""
												+ DisPerValue);
									}

									// fill in the grid_item layout
									fillMapstrdes.add(maptrdes);
									SimpleAdapter adaptertrdes = new SimpleAdapter(
											this,
											fillMapstrdes,
											R.layout.dm_bbm_outlet_discount_summary_raw,
											fromtrdes, totrdes);
									lvtypedes.setAdapter(adaptertrdes);
								}

							}
						}
						// Display Current Date Summary

						DateDiscountValue = DateDiscountValue.setScale(2,
								BigDecimal.ROUND_HALF_DOWN);
						DateSalesDisPer = DateSalesDisPer.setScale(2,
								BigDecimal.ROUND_HALF_DOWN);
						DateSalesOrdValue = DateSalesOrdValue.setScale(2,
								BigDecimal.ROUND_HALF_DOWN);

						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("item_result_0", "");
						maptrdes.put("item_result_1", "");
						maptrdes.put("item_result_2", "Total");
						maptrdes.put("item_result_3", "" + DateSalesOrdValue);
						maptrdes.put("item_result_4", "" + DateDiscountValue);
						maptrdes.put("item_result_5", "" + DateSalesDisPer);

						// fill in the grid_item layout
						fillMapstrdes.add(maptrdes);
						SimpleAdapter adaptertrdes = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_bbm_outlet_discount_summary_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdes);

						// Add dummy seperator
						HashMap<String, String> maptrdesdum = new HashMap<String, String>();
						maptrdesdum.put("item_result_0", "");
						maptrdesdum.put("item_result_1", "");
						maptrdesdum.put("item_result_2", "");
						maptrdesdum.put("item_result_3", "");
						maptrdesdum.put("item_result_4", "");
						maptrdesdum.put("item_result_5", "");

						fillMapstrdes.add(maptrdesdum);
						SimpleAdapter adaptertrdesdum = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_bbm_outlet_discount_summary_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdesdum);

						// TotalDiscountValue,TotalTaxValue,TotalSalesOrdValue
						TotalDiscountValue = TotalDiscountValue
								.add(DateDiscountValue);
						TotalSalesDisPer = TotalSalesDisPer.add(DateSalesDisPer);
						TotalSalesOrdValue = TotalSalesOrdValue
								.add(DateSalesOrdValue);

						DateDiscountValue = new BigDecimal("0.00");
						DateSalesDisPer = new BigDecimal("0.00");
						DateSalesOrdValue = new BigDecimal("0.00");
					}
				}
			}
		}
		/************ Display Report Summary *********************/

		TotalDiscountValue = TotalDiscountValue.setScale(2,
				BigDecimal.ROUND_HALF_DOWN);
		DateSalesDisPer = DateSalesDisPer.setScale(2,
				BigDecimal.ROUND_HALF_DOWN);
		TotalSalesOrdValue = TotalSalesOrdValue.setScale(2,
				BigDecimal.ROUND_HALF_DOWN);

		HashMap<String, String> maptrdes = new HashMap<String, String>();
		maptrdes.put("item_result_0", "");
		maptrdes.put("item_result_1", "");
		maptrdes.put("item_result_2", "Grand Total");
		maptrdes.put("item_result_3", "" + TotalSalesOrdValue);
		maptrdes.put("item_result_4", "" + TotalDiscountValue);
		maptrdes.put("item_result_5", "" + DateSalesDisPer);

		// fill in the grid_item layout
		fillMapstrdes.add(maptrdes);
		SimpleAdapter adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
				R.layout.dm_bbm_outlet_discount_summary_raw, fromtrdes, totrdes);
		lvtypedes.setAdapter(adaptertrdes);
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub

		Intent myIntent = new Intent(DM_BBM_Outlet_Discount_Summary.this,
				DM_BBM_Reports_Generator.class);
		myIntent.putExtra("TAGID", "0/SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}
}
